#include "gstreamer_3.h"

typedef struct _CustomData
{
    GstElement * pipeline;
    GstElement * source;
    GstElement * audio_convert;
    GstElement * audio_resample;
    GstElement * audio_sink;

    GstElement * video_convert;
    GstElement * video_sink;

} CustomData;

static void pad_added_handler(GstElement *, GstPad *, CustomData *);

int play_02(int argc, char *argv[])
{
    CustomData data;
    GstBus * bus;
    GstMessage * message;
    GstStateChangeReturn ret;
    gboolean terminal = false;

    gst_init(&argc, &argv);

    data.source = gst_element_factory_make("uridecodebin", "source");
    data.audio_convert = gst_element_factory_make("audioconvert", "audio-convert");
    data.audio_resample = gst_element_factory_make("audioresample", "audio-resample");
    data.audio_sink = gst_element_factory_make("autoaudiosink", "audio-sink");
    
    data.video_convert = gst_element_factory_make("videoconvert", "video-convert");
    data.video_sink = gst_element_factory_make("autovideosink", "video-sink");

    data.pipeline = gst_pipeline_new("test-pipeline");

    if(!data.pipeline || !data.source || !data.audio_convert || !data.audio_resample || !data.audio_sink || !data.video_convert || !data.video_sink) {
        g_printerr("Not all elements could be created!\n");
        return -1;
    }

    gst_bin_add_many(GST_BIN(data.pipeline), data.source, data.video_convert, data.video_sink, data.audio_convert, data.audio_resample, data.audio_sink, nullptr);
    if(!gst_element_link_many(data.audio_convert, data.audio_resample, data.audio_sink, nullptr)) {
        g_printerr("Audio elements could not be linked!\n");
        g_object_unref(data.pipeline);
        return -1;
    }
    if(!gst_element_link_many(data.video_convert, data.video_sink, nullptr)) {
        g_printerr("Video elements could not be linked!\n");
        g_object_unref(data.pipeline);
        return -1;
    }

    g_object_set(data.source, "uri", "https://gstreamer.freedesktop.org/data/media/sintel_trailer-480p.webm", nullptr);

    g_signal_connect(data.source, "pad-added", G_CALLBACK(pad_added_handler), &data);

    ret = gst_element_set_state(data.pipeline, GST_STATE_PLAYING);
    if(ret == GST_STATE_CHANGE_FAILURE) {
        g_printerr("Unable to set the pipeline to playing state.\n");
        g_object_unref(data.pipeline);
        return -1;
    }

    bus = gst_element_get_bus(data.pipeline);
    do {
        message = gst_bus_timed_pop_filtered(bus, GST_CLOCK_TIME_NONE, (GstMessageType)(GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_STATE_CHANGED));

        if(message) {
            GError * err;
            char* debug_info;

            switch(GST_MESSAGE_TYPE(message)) {
                case GST_MESSAGE_ERROR:
                    gst_message_parse_error(message, &err, &debug_info);
                    g_printerr("Error received from element %s:%s\n", GST_OBJECT_NAME(message->src), err->message);
                    g_printerr("Debugging information: %s\n",debug_info ? debug_info : "none");
                    g_clear_error(&err);
                    g_free(debug_info);
                    terminal = true;
                    break;
                case GST_MESSAGE_EOS:
                    g_print("End of stream has been reached!\n");
                    terminal = true;
                    break;
                case GST_MESSAGE_STATE_CHANGED:
                    if(GST_MESSAGE_SRC(message) == GST_OBJECT(data.pipeline)) {
                        GstState old_state, new_state, pending_state;
                        gst_message_parse_state_changed(message, &old_state, &new_state, &pending_state);
                        g_print("Pipeline state change from %s to %s.\n", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
                    }
                    break;
                default:
                    g_printerr("Unexcepted message received!\n");
                    break;
            }
            gst_message_unref(message);
        }
    } while(!terminal);
    
    gst_object_unref(bus);
    gst_element_set_state(data.pipeline, GST_STATE_NULL);
    gst_object_unref(data.pipeline);

    return 0;
}

static void pad_added_handler(GstElement * src, GstPad * new_pad, CustomData * data) {
    // new_pad 需要和sink_pad 连接
    GstPad * audio_sink_pad = gst_element_get_static_pad(data->audio_convert, "sink");
    GstPad * video_sink_pad = gst_element_get_static_pad(data->video_convert, "sink");
    GstPadLinkReturn ret;
    GstCaps * new_pad_caps = nullptr;
    GstStructure * new_pad_struct = nullptr;
    const char * new_pad_type = nullptr;

    g_print("Received new pad %s from %s.\n", GST_PAD_NAME(new_pad), GST_ELEMENT_NAME(src));

    if(gst_pad_is_linked(new_pad)) {
        g_printerr("new_pad was already linked. Ignoring.\n");
        goto exit;
    }

    new_pad_caps = gst_pad_get_current_caps(new_pad);
    new_pad_struct = gst_caps_get_structure(new_pad_caps, 0);
    new_pad_type = gst_structure_get_name(new_pad_struct);
    if(!g_str_has_prefix(new_pad_type, "audio/x-raw") && !g_str_has_prefix(new_pad_type, "video/x-raw")) {
        g_printerr("It has type '%s' which is not raw audio. Ignoring.\n", new_pad_type);
        goto exit;
    }

    ret = gst_pad_link(new_pad, g_str_has_prefix(new_pad_type, "audio/x-raw") ? audio_sink_pad: video_sink_pad);
    if(GST_PAD_LINK_FAILED(ret)) {
        g_print("Type is %s but link failed.\n", new_pad_type);
    } else {
        g_print("Link successed.(type '%s')\n", new_pad_type);
    }

exit:
    if(new_pad_caps != nullptr) {
        gst_caps_unref(new_pad_caps);
    }
    g_object_unref(audio_sink_pad);
}